/*
 * @Descripttion: xxx
 * @version: 1.0.0
 * @Date: 2022-02-17 11:20:06
 * @LastEditTime: 2022-05-06 18:50:05
 */
export function filterObjectProp(obj: object) {
  const newObj = {};
  Object.keys(obj).forEach((key) => {
    const value = obj[key];
    value && value != 0 && (newObj[key] = value);
  });
  return newObj;
}

export function createGuid() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (
    S4() +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    S4() +
    S4()
  );
}

export function getRandomNum(Min: number, Max: number) {
  const Range = Max - Min,
    Rand = Math.random();
  return Min + Math.round(Rand * Range);
}

// 节流throttle代码（时间戳+定时器）：
export function throttle(func: (args?) => void, delay = 0) {
  let timer: null | NodeJS.Timeout = null;
  let startTime = Date.now();
  return () => {
    const curTime = Date.now();
    const remaining = delay - (curTime - startTime);

    timer && clearTimeout(timer);
    if (remaining <= 0) {
      func();
      startTime = Date.now();
    } else {
      timer = setTimeout(() => func, remaining);
    }
  };
}

// 防抖
export function debounce(func: (args?) => void, wait = 0) {
  if (typeof func !== "function") {
    throw new TypeError("need a function arguments");
  }
  let timeid: null | NodeJS.Timeout = null;
  let result;

  return () => {
    if (timeid) {
      clearTimeout(timeid);
    }
    timeid = setTimeout(function () {
      func();
    }, wait);

    return result;
  };
}

export function getType(
  obj: any
): "String" | "Date" | "Number" | "Boolean" | "Array" | "Object" {
  const type = typeof obj;
  if (type == "string" && new Date(obj).toString() !== "Invalid Date") {
    return "Date";
  }
  // 可以通过Object.prototype.toString方法，判断某个对象之属于哪种内置类型。 "[object Null]"
  // @ts-ignore
  return Object.prototype.toString
    .call(obj)
    .replace(/^\[object (\S+)\]$/, "$1");
}
